<?php

/*
	Class: Commerce_AccountController

	About: Author
		Rich Joslin
*/
class Commerce_AccountController extends Commerce_Controller_Action {

	/*
		Function: init
	*/
	function init(){	
		parent::init();				
	}

	/* Group: Actions */

	/*
		Function: overview
	*/
	function overviewAction() {
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$errors = array();
			$customers_table = new CommerceMagentoCustomers();
			$commerce_users_table = new CommerceUsers();
			$newsletter_table = new CommerceMagentoNewsletter();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			if (count($commerce_user) > 0) {
				$customer = $customers_table->getCustomerInfo($commerce_user['commerce_customer_id']);
				$this->view->is_subscribed = $newsletter_table->isCustomerSubscribed($commerce_user['commerce_customer_id']);
				$this->view->customer = $customer;
			}
			$this->view->commerce_user = $commerce_user;
			$this->view->current_nav = 'overview';
			$this->view->errors = $errors;
		}
	}

	/*
		Function: profile
	*/
	function profileAction() {
		$request = new Cts_Request($this->getRequest());
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$customers_table = new CommerceMagentoCustomers();
			$cts_users_table = new Users();
			$commerce_users_table = new CommerceUsers();
			$newsletter_table = new CommerceMagentoNewsletter();

			$cts_user = $cts_users_table->findArray($this->_identity->username);
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$magento_customer = $customers_table->getCustomerInfo($commerce_user['commerce_customer_id']);
			$errors = array();

			if ($this->getRequest()->isPost()) {
				// VALIDATE POST VALUES
				$request->addValidator('first_name', $this->_T('First name is required.'));
				$request->addValidator('last_name', $this->_T('Last name is required.'));
				$request->addValidator('email', $this->_T('Email is required.'));
				$email_validator = new Zend_Validate_EmailAddress();
				if (!$email_validator->isValid($request->email)) {
					$errors[] = 'The email address entered is not a valid email address.';
				}
				// IF A NEW PASSWORD IS ENTERED, VALIDATE THE PASSWORD CONFIRMATION FIELD
				if ($request->password != '') {
					$request->addValidator('confirm_password', $this->_T('Password confirmation is required.'));
					if ($request->password != $request->confirm_password) {
						$errors[] = 'Passwords entered did not match.';
					}
				}
				if ($request->email != $cts_user['email'] && $cts_users_table->isEmailInUse($request->email)) {
					$errors[] = 'The email you entered is already in use by someone else.';
				}
				if (!$request->isValid()) {
					$errors = array_merge($errors, $request->getValidationErrors());
				}

				// APPLY THE CHANGES TEMPORARILY
				$magento_customer = array(
					'firstname' => $request->first_name,
					'lastname' => $request->last_name,
					'email' => $request->email,
				);
				$commerce_user['first_name'] = $request->first_name;
				$commerce_user['last_name'] = $request->last_name;
				$commerce_user['last_modified_on'] = date(DB_DATETIME_FORMAT);
				$cts_user['full_name'] = $request->first_name.' '.$request->last_name;
				$cts_user['email'] = $request->email;
				$cts_user['last_modified_on'] = date(DB_DATETIME_FORMAT);

				if (count($errors) == 0) {
					// APPLY PROFILE CHANGES IN THREE PLACES

					// CHANGE THE PASSWORD IF APPLICABLE
					if (isset($request->password) && $request->password != '') {
						$customers_table->setPassword($commerce_user['commerce_customer_id'], $request->password);
						$cts_user['password'] = $request->password;
					}

					// UPDATE MAGENTO
					$customers_table->update($commerce_user['commerce_customer_id'], $magento_customer);

					// UPDATE THE COMMUNITAS COMMERCE USERS TABLE
					unset($commerce_user['username']);
					$where = $commerce_users_table->getAdapter()->quoteInto('username = ?', $this->_identity->username);
					$commerce_users_table->update($commerce_user, $where);

					// UPDATE THE COMMUNITAS USERS TABLE
					unset($cts_user['username']);
					$where = $cts_users_table->getAdapter()->quoteInto('username = ?', $this->_identity->username);
					$cts_users_table->update($cts_user, $where);

					// DONE
					$this->_redirect('/commerce/account/overview');
				}
			}

			$this->view->commerce_user = $commerce_user;
			$this->view->customer = $magento_customer;
			$this->view->communitas_user = $cts_user;
			$this->view->is_subscribed = $newsletter_table->isEmailSubscribed($this->_loggedInUser->email);
			$this->view->current_nav = 'profile';
		}
		$this->view->errors = $errors;
	}

	/*
		Function: addressbook
	*/
	function addressbookAction() {
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$commerce_users_table = new CommerceUsers();
			$customers_table = new CommerceMagentoCustomers();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$tmp_addresses = $customers_table->getAddressBook($commerce_user['commerce_customer_id']);
			$this->view->addresses = $tmp_addresses;
			$this->view->current_nav = 'addressbook';
		}
	}

	/*
		Function: editaddressAction
	*/
	function editaddressAction() {
		$request = new Cts_Request($this->getRequest());
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$commerce_users_table = new CommerceUsers();
			$customers_table = new CommerceMagentoCustomers();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$customer_id = $commerce_user['commerce_customer_id'];
			if ($this->getRequest()->isPost()) {
				// POSTING ADDRESS CHANGES
				$address = array(
					'address_id' => $request->id,
					'firstname' => $request->firstname,
					'lastname' => $request->lastname,
					'street' => $request->street,
					'city' => $request->city,
					'region_id' => $request->region_id,
					'postcode' => $request->postcode,
					'country_id' => $request->country_id,
					'telephone' => $request->telephone,
				);
				$errors = array();
				$request->addValidator("firstname", $this->_T("First name is required."));
				$request->addValidator("lastname", $this->_T("Last name is required."));
				$request->addValidator("street", $this->_T("Street is required."));
				$request->addValidator("city", $this->_T("City is required."));
				$request->addValidator("region_id", $this->_T("State is required."));
				$request->addValidator("postcode", $this->_T("Post code is required."));
				$request->addValidator("country_id", $this->_T("Country is required."));
				$request->addValidator("telephone", $this->_T("Phone number is required."));
				if (!$request->isValid()) {
					$errors = array_merge($errors, $request->getValidationErrors());
				}
				if (count($errors) == 0) {
					if ($request->id > 0) {
						$address_id = $request->id;
						// IMPORTANT : MAKE SURE THE ADDRESS BELONGS TO THE LOGGED-IN USER
						$test_address = $customers_table->getAddressInfo($address_id);
						if ($test_address['customer_id'] != $customer_id) {
		 					$this->_redirect("/default/auth/missing");
						}
						// UPDATE
						$result = $customers_table->updateAddress($address_id, $address);
					} else {
						// INSERT
						$new_address_id = $customers_table->createAddress($customer_id, $address);
					}
					$this->_redirect('/commerce/account/addressbook');
				}
			} elseif ($request->has('id') && $request->id > 0) {
				// EDITING AN EXISTING ADDRESS
				$address_id = $request->id;
				$address = $customers_table->getAddressInfo($address_id);
				// IMPORTANT : MAKE SURE THE ADDRESS BELONGS TO THE LOGGED-IN USER
				if ($address['customer_id'] != $customer_id) {
 					$this->_redirect("/default/auth/missing");
				}
			} else {
				// CREATING A NEW ADDRESS
				$address = array(
					'address_id' => '0',
					'firstname' => '',
					'lastname' => '',
					'street' => '',
					'city' => '',
					'region_id' => '',
					'postcode' => '',
					'country_id' => 'US',
					'telephone' => '',
				);
			}

			$this->view->address = $address;
			$this->view->errors = $errors;

			$countries_table = new CommerceMagentoCountries();
			$tmp_countries = $countries_table->getCountries();
			$countries = array();
			foreach ($tmp_countries as $tmp_country) {
				$countries[$tmp_country['country_id']] = $tmp_country['name'];
			}
			$this->view->countries = $countries;

			if (isset($address['country_id'])) {
				$regions_table = new CommerceMagentoRegions();
				$tmp_regions = $regions_table->getRegions($address['country_id']);
				$regions = array('' => 'Select a State...');
				foreach ($tmp_regions as $tmp_region) {
					$regions[$tmp_region['region_id']] = $tmp_region['name'];
				}
				$this->view->regions = $regions;
			}

			$this->view->current_nav = 'addressbook';
		}
	}

	/*
		Function: deleteaddress
	*/
	function deleteaddressAction() {
		$request = new Cts_Request($this->getRequest());
		if (is_null($this->_loggedInUser) || !$request->has('id')) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$address_id = $request->id;
			$commerce_users_table = new CommerceUsers();
			$customers_table = new CommerceMagentoCustomers();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$customer_id = $commerce_user['commerce_customer_id'];
			$address = $customers_table->getAddressInfo($address_id);
			// IMPORTANT : MAKE SURE THE ADDRESS BELONGS TO THE LOGGED-IN USER
			if ($address['customer_id'] != $customer_id) {
				$this->_redirect("/default/auth/missing");
			}
			if ($this->getRequest()->isPost()) {
				// DELETE
				$del = strtolower($request->delete);			
				if ($del == 'yes' && !is_null($address_id)) {
					$customers_table->deleteAddress($address_id);
				}
				$this->_redirect('/commerce/account/addressbook');
			}
			$this->view->address = $address;
			$this->view->current_nav = 'addressbook';
		}
	}

	/*
		Function: orders
	*/
	function ordersAction() {
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$commerce_users_table = new CommerceUsers();
			$orders_table = new CommerceMagentoOrders();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$tmp_orders = $orders_table->getOrders(array('customer_id' => $commerce_user['commerce_customer_id']));
			$orders = array();
			foreach ($tmp_orders as $tmp_order) {
				$order = array();
				$order['order_number'] = $tmp_order['increment_id'];
				$tmp_shipments = $orders_table->getShipments($order['order_number']);
				if (count($tmp_shipments) > 0) {
					$order['shipment_status'] = $this->_T('Shipped');
					$order['shipment_status_date'] = $tmp_shipments[0]['created_at'];
				} else {
					$order['shipment_status'] = $this->_T('Processing');
				}
				$orders[] = $order;
			}
			$this->view->orders = $orders;
			$this->view->current_nav = 'orders';
		}
	}

	/*
		Function: orderdetail
	*/
	function orderdetailAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('id') || is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$commerce_users_table = new CommerceUsers();
			$orders_table = new CommerceMagentoOrders();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$tmp_order = $orders_table->getOrderInfo($request->id);
			// IMPORTANT: Make sure this order belongs to the logged-in user.
			if ($tmp_order['customer_id'] != $commerce_user['commerce_customer_id']) {
				// this is not your order - you get the boot
 				$this->_redirect("/default/auth/missing");
			} else {
				$this->view->order = $tmp_order;
			}
			$this->view->current_nav = 'orders';
		}
	}

	/*
		Function: newsletter
	*/
	function newsletterAction() {
		$request = new Cts_Request($this->getRequest());
		if (is_null($this->_loggedInUser)) {
 			$this->_redirect("/default/auth/missing");
		} else {
			$commerce_users_table = new CommerceUsers();
			$newsletter_table = new CommerceMagentoNewsletter();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
			$is_subscribed = $newsletter_table->isCustomerSubscribed($commerce_user['commerce_customer_id']);
			if ($this->getRequest()->isPost()) {
				// only make a change if a change needs to be made
				// don't want to make an unnecessary SOAP call
				if (is_null($request->subscribe_hotwire) && $is_subscribed == 1) {
					// UNSUBSCRIBE
					$result = $newsletter_table->unsubscribe($this->_loggedInUser->email);
					$this->view->success = 'Successfully unsubscribed from Hotwire.';
					$is_subscribed = false;
				} elseif (!is_null($request->subscribe_hotwire) && $is_subscribed == 0) {
					// SUBSCRIBE
					$result = $newsletter_table->subscribe($this->_loggedInUser->email);
					$this->view->success = 'Thanks for subscribing!';
					$is_subscribed = true;
				} else {
					$this->view->notice = 'No change was made.';
				}
			}
			$this->view->is_subscribed = $is_subscribed;
			$this->view->current_nav = 'newsletter';
		}
	}

	/*
		Function: subscribe
	*/
	function subscribeAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if ($this->getRequest()->isPost() && $request->has('newsletter_email')) {
			if (Cts_Validate::checkEmail($request->newsletter_email)) {
				$newsletter_table = new CommerceMagentoNewsletter();
				$newsletter_table->subscribe($request->newsletter_email);
				$this->view->success = 'Thanks for subscribing!';
			} else {
				$errors[] = 'Invalid email address.';
			}
		}
		$this->view->errors = $errors;
	}

}
